package com.cooba.activitys.integral;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cooba.R;
import com.cooba.activitys.user.ChangNumberActivity;
import com.cooba.bean.GoodsExchangeBean;
import com.cooba.bean.UserAddressBean;
import com.cooba.utils.CommonUtil;
import com.cooba.utils.Constants;
import com.cooba.utils.ServerURL;
import com.cooba.utils.SharedPreferencesUtil;
import com.cooba.utils.Utils;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.PushAgent;

import org.w3c.dom.Text;

/**
 * Created by Administrator on 2016/6/14.
 */
public class ComfirmExchangeActivity extends AppCompatActivity implements View.OnClickListener {
    private static final int REQUEST_CODE = 0;
    private String goods_icon;
    private String goods_name;
    private String goods_desc;
    private String goods_num;
    private String goods_need_integral;
    private String goods_ex_type;
    private String goods_public_time;
    private String goods_valid_time;

    private TextView mGoods_name;
    private TextView mGoods_num;
    private TextView mGoods_need_integral;
    private ImageButton mGoods_back;
    private ImageView mGoods_icon;
    private TextView mGoods_extype;
    private TextView mGoods_time;
    private TextView mGoods_update_address;
    private TextView mGoods_reciver_address;
    private EditText mGoods_remark;
    private TextView mGoods_exchange_btn;
    private BitmapUtils bitmapUtils;
    private HttpUtils httpUtils;
    private RequestParams params;
    private UserAddressBean userAddressBean;
    private String goods_id;
    private String addressId;
    private TextView mGoods_desc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_exchange_comfirm);

        PushAgent.getInstance(this).onAppStart();

        bitmapUtils = new BitmapUtils(this);
        Bundle bundle = getIntent().getBundleExtra("goods_data");
        goods_id=bundle.getString("goods_id");
        goods_icon = bundle.getString("goods_icon");
        goods_name = bundle.getString("goods_name");
        goods_num = bundle.getString("goods_num");
        goods_need_integral = bundle.getString("goods_need_integral");
        goods_ex_type = bundle.getString("goods_ex_type");
        goods_public_time = bundle.getString("goods_public_date");
        goods_valid_time = bundle.getString("goods_valid_date");
        goods_desc=bundle.getString("goods_desc");
        initView();
        setListener();
        setData();
        getAddress();
    }

    private void getAddress() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        String login_id=SharedPreferencesUtil.getData(this,"login_id","");
        params.addBodyParameter("login_id", login_id);
        String urladdress = ServerURL.httpUrl + ServerURL.userReciverAddress;
        httpUtils.send(HttpRequest.HttpMethod.POST, urladdress, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "获取地址失败");
                Toast.makeText(ComfirmExchangeActivity.this, "无网络!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "获取地址成功" + responseInfo.result);
                try {
                    userAddressBean = new Gson().fromJson(responseInfo.result, UserAddressBean.class);
                    if (userAddressBean.getAddress() != null) {
                        mGoods_reciver_address.setText(userAddressBean.getAddress().replaceAll("@", ""));
                        addressId = userAddressBean.getId();
                    } else {
                        mGoods_reciver_address.setText("暂未设置收货地址");
                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void setListener() {
        mGoods_back.setOnClickListener(this);
        mGoods_exchange_btn.setOnClickListener(this);
        mGoods_update_address.setOnClickListener(this);
    }

    private void setData() {
        bitmapUtils.display(mGoods_icon, ServerURL.host + goods_icon);
        mGoods_name.setText(goods_name);
        mGoods_num.setText(goods_num);
        mGoods_need_integral.setText(goods_need_integral);
        mGoods_extype.setText(goods_ex_type);
        mGoods_desc.setText(goods_desc);
        mGoods_time.setText(goods_public_time.substring(0, 10) + "至" + goods_valid_time.substring(0, 10));

    }

    private void initView() {
        mGoods_back = (ImageButton) findViewById(R.id.goods_exchange_comfirm_back_ib);
        mGoods_name = (TextView) findViewById(R.id.goods_exchange_comfirm_name);
        mGoods_num = (TextView) findViewById(R.id.goods_exchange_comfirm_num);
        mGoods_need_integral = (TextView) findViewById(R.id.goods_exchange_comfirm_need_integral);
        mGoods_icon = (ImageView) findViewById(R.id.goods_exchange_comfirm_icon);
        mGoods_extype = (TextView) findViewById(R.id.goods_exchange_comfirm_ex_type);
        mGoods_desc= (TextView) findViewById(R.id.goods_exchange_comfirm_desc);
        mGoods_time = (TextView) findViewById(R.id.goods_exchange_comfirm_time);
        mGoods_update_address = (TextView) findViewById(R.id.goods_exchange_comfirm_update_address);
        mGoods_reciver_address = (TextView) findViewById(R.id.goods_exchange_comfirm_reciver_address);
        mGoods_remark = (EditText) findViewById(R.id.goods_exchange_comfirm_remark);
        mGoods_exchange_btn = (TextView) findViewById(R.id.goods_exchange_comfirm_btn);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.goods_exchange_comfirm_back_ib:
                finish();
                break;
            case R.id.goods_exchange_comfirm_btn:
                startExchange();
                break;
            case R.id.goods_exchange_comfirm_update_address:
                Intent intent=new Intent(ComfirmExchangeActivity.this,UserAddressUpdateActivity.class);
                startActivityForResult(intent, REQUEST_CODE);
                break;
            default:
                break;
        }
    }

    private void startExchange() {
        httpUtils = new HttpUtils();
        params = new RequestParams();
        String mac= SharedPreferencesUtil.getData(this,"wifimac","");
        String login_id=SharedPreferencesUtil.getData(this,"login_id","");
        String login_state=SharedPreferencesUtil.getData(this,"login_state","0");
        if (TextUtils.isEmpty(login_id)&&login_state.equals("0")) {
            Toast.makeText(this, "未登录!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!Utils.isnumber(login_id)){
            showBindDialog();
            return;
        }
        if (TextUtils.isEmpty(addressId)){
            Toast.makeText(this,"尚未绑定地址!",Toast.LENGTH_SHORT).show();
            return;
        }
        params.addBodyParameter("login_id", login_id);
        params.addBodyParameter("product_id",goods_id);
        params.addBodyParameter("ex_info_id",addressId);
        params.addBodyParameter("remark",mGoods_remark.getText().toString().trim());
        params.addBodyParameter("mac",mac);
        String goodsexchangeurl = ServerURL.httpUrl + ServerURL.goodsExchange;
        httpUtils.send(HttpRequest.HttpMethod.POST, goodsexchangeurl, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                Log.e("wei", "链接服务器失败");
                Toast.makeText(ComfirmExchangeActivity.this, "无网络!", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Log.e("wei", "兑换成功" + responseInfo.result);
                String msg = null;
                try {
                    msg = JSON.parseObject(responseInfo.result).getString("msg");
                    String status = JSON.parseObject(responseInfo.result).getString("status");
                    if (status.equals("1")) {
                        String exstatus = JSON.parseObject(responseInfo.result).getString("ex_status");
                        if (exstatus!=null&&exstatus.equals("0")){
                            Toast.makeText(ComfirmExchangeActivity.this, msg, Toast.LENGTH_SHORT).show();
                        }else {
                            Toast.makeText(ComfirmExchangeActivity.this, "兑换成功!", Toast.LENGTH_SHORT).show();
                            String integralTotal = JSON.parseObject(responseInfo.result).getString("integralTotal");
                            SharedPreferencesUtil.saveData(ComfirmExchangeActivity.this, "allTotalIntegral", integralTotal);
                            Intent intent = new Intent(Constants.UPDATE_DATA);
                            sendBroadcast(intent);
                            finish();
                        }
                    }else {
                        Toast.makeText(ComfirmExchangeActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    //显示绑定对话框
    public void showBindDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(ComfirmExchangeActivity.this);
        builder.setTitle("尚未绑定手机号,是否绑定?");
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(ComfirmExchangeActivity.this, ChangNumberActivity.class);
                startActivity(intent);
            }
        });
        AlertDialog dialog = builder.create();
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_CODE) {
            String updateaddress=data.getStringExtra("update_address");
            String address_id=data.getStringExtra("address_id");
            if (updateaddress != null&&address_id!=null) {
                Log.d("wei--", updateaddress);
                addressId=address_id;
                mGoods_reciver_address.setText(updateaddress.replaceAll("@",""));
            }
        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}
